import React, { Component } from 'react';
import { indexOf, isFunction } from 'lodash';
import findup from 'findup-element';
import styleO from '/common/components/EditableTable/index.less';
import { Button, Col, Icon, Row } from 'antd';

class ContextMenu extends Component {

  constructor(props) {
    super(props);
    this.state = { visible: false };
  }

  // componentDidMount() {
  //   document.addEventListener('contextmenu', this._handleContextMenu);
  //   document.addEventListener('click', this._handleClick);
  //   document.addEventListener('scroll', this._handleScroll);
  // }
  //
  // componentWillUnmount() {
  //   document.removeEventListener('contextmenu', this._handleContextMenu);
  //   document.removeEventListener('click', this._handleClick);
  //   document.removeEventListener('scroll', this._handleScroll);
  // }

  _handleContextMenu = (event) => {
    event.preventDefault();

    this.setState({ visible: true });

    const clickX = event.clientX;
    const clickY = event.clientY;
    const screenW = window.innerWidth;
    const screenH = window.innerHeight;
    const rootW = this.root.offsetWidth;
    const rootH = this.root.offsetHeight;

    const right = (screenW - clickX) > rootW;
    const left = !right;
    const top = (screenH - clickY) > rootH;
    const bottom = !top;

    if (right) {
      this.root.style.left = `${clickX + 5}px`;
    }

    if (left) {
      this.root.style.left = `${clickX - rootW - 5}px`;
    }

    if (top) {
      this.root.style.top = `${clickY + 5}px`;
    }

    if (bottom) {
      this.root.style.top = `${clickY - rootH - 5}px`;
    }
  };

  _handleClick = (event) => {
    const { visible } = this.state;
    const wasOutside = !(event.target.contains === this.root);

    if (wasOutside && visible) this.setState({ visible: false });
  };

  _handleScroll = () => {
    const { visible } = this.state;

    if (visible) this.setState({ visible: false });
  };

  render() {
    return (
      <div
        onContextMenu={this._handleContextMenu.bind(this)}
        style={this.props.style || {}}>
        {this.props.children}
        <div
          ref={ref => {
            this.root = ref;
          }}
          style={ {display: this.state.visible?'block':'none', ...(this.props.contentStyle || {})}  }
          className={styleO.contextMenu}>
          {
            this.props.content
          }
        </div>
      </div>
    );
  }
}

ContextMenu.defaultProps = {
  style: {},
  contentStyle: {},
  content: null,
};

export default ContextMenu;
